<template>
  <div class="container  question-new">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <!-- <span>{{ $route.params.id ? '试题修改' : '试题录入' }}</span> -->
        <span>{{ $route.query.id ? '试题修改' : '试题录入' }}</span>
      </div>
      <div class="content">
        <el-form
          ref="form"
          :model="qsForm"
          :rules="qsRules"
          label-width="100px"
          label-position="right"
        >
          <!-- 学科 -->
          <el-form-item label="学科：" prop="subjectID">
            <el-select
              v-model="qsForm.subjectID"
              placeholder="请选择学科"
              style="width: 400px;"
              @focus="showSubjectsList"
              @change="subjectsChange"
            >
              <el-option
                v-for="item in subjectsList"
                :key="item.id"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- 目录 -->
          <el-form-item label="目录：" prop="catalogID">
            <el-select
              v-model="qsForm.catalogID"
              style="width: 400px;"
              placeholder="请选择目录"
            >
              <el-option
                v-for="item in catalogList"
                :key="item.value"
                :label="item.label"
                :value="item.value"
              />
            </el-select>
          </el-form-item>

          <!-- 企业 -->
          <el-form-item label="企业：" prop="enterpriseID">
            <el-select
              v-model="qsForm.enterpriseID"
              style="width: 400px;"
              placeholder="请选择企业"
              @focus="clickEnterprise"
            >
              <el-option
                v-for="item in enterpriseList"
                :key="item.id"
                :label="item.company"
                :value="item.id"
              />
            </el-select>
          </el-form-item>

          <!-- 城市  （市，地区）选择器  级联（选项与选项之间有从属关系)-->
          <el-form-item label="城市：" prop="city">
            <el-select
              v-model="qsForm.province"
              style="width: 195px;margin-right: 10px;"
              placeholder="请选择城市"
              filterable
              @change="getCityList"
            >
              <el-option
                v-for="(item, index) in provinceList"
                :key="index"
                :label="item"
                :value="item"
              />
            </el-select>
            <el-select
              v-model="qsForm.city"
              style="width: 195px;"
              placeholder="请选择地区"
              filterable
            >
              <el-option
                v-for=" item in citysList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <!-- 方向  -->
          <el-form-item label="方向：" prop="direction">
            <el-select
              v-model="qsForm.direction"
              style="width: 400px;"
              placeholder="请选择方向"
            >
              <el-option
                v-for="item in directionList"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
          </el-form-item>

          <!-- 题型  单选框-->
          <el-form-item label="题型：" prop="questionType">
            <el-radio
              v-for="item in questionType"
              :key="item.value"
              v-model="qsForm.questionType"
              :label="item.value + ''"
              @change="changeQuestionType"
            >{{ item.label }}</el-radio>
          </el-form-item>

          <!-- 难度  单选框-->
          <el-form-item label="难度：" prop="difficulty">
            <el-radio
              v-for="item in difficulty"
              :key="item.value"
              v-model="qsForm.difficulty"
              :label="item.value + ''"
            >{{ item.label }}</el-radio>
          </el-form-item>

          <!-- 题干  富文本-->
          <el-form-item label="题干：" prop="question">
            <!-- 富文本编辑器 -->
            <!-- <el-input placeholder="这里是富文本" style="width: 400px;" /> -->
            <quill-editor
              ref="text"
              v-model="qsForm.question"
              class="myQuillEditor"
              :options="editorOption"
            />
          </el-form-item>

          <!-- 选项   需要分情况和试题类型关联 -->
          <el-form-item v-if="qsForm.questionType !== '3'" label="选项：">
            <div
              v-for="item in qsForm.options"
              :key="item.code"
              style="margin-top: 30px;"
            >
              <el-radio
                v-if="qsForm.questionType === '1'"
                v-model="item.isRight"
                :label="true"
                style="margin: 0;"
                @change="changeRadio(item)"
              >{{ item.code }}：</el-radio>
              <el-checkbox
                v-if="qsForm.questionType === '2'"
                v-model="item.isRight"
                style="margin: 0;"
                :label="true"
              >{{ item.code }}：</el-checkbox>
              <el-input v-model="item.title" style="width: 240px;" />

              <!-- 上传头像 -->
              <el-upload
                class="avatar-uploader"
                action="https://jsonplaceholder.typicode.com/posts/"
                :show-file-list="false"
              >
                <img v-if="item.img" :src="item.img" class="avatar">
                <span v-else>上传头像</span>
                <i class="el-icon-circle-close" />
              </el-upload>

            </div>
            <!-- 增加选项与答案按钮 -->
            <el-button
              :disabled="qsForm.questionType !== '2'"
              type="danger"
              size="small"
              style="margin-top: 20px;"
              @click="clickOption"
            >+增加选项与答案</el-button>
          </el-form-item>

          <!-- 解析视频 -->
          <el-form-item label="解析视频：" prop="videoURL">
            <el-input v-model="qsForm.videoURL" style="width: 400px;" />
          </el-form-item>

          <!-- 答案解析  富文本-->
          <el-form-item label="答案解析：" prop="answer">
            <!-- <el-input style="width: 400px;" placeholder="这里是答案备注富文本" /> -->
            <quill-editor ref="text" v-model="qsForm.answer" class="myQuillEditor" :options="editorOption" />
          </el-form-item>

          <!-- 题目备注 -->
          <el-form-item label="题目备注：" prop="remarks">
            <el-input
              v-model="qsForm.remarks"
              style="width: 400px;"
              type="textarea"
              :rows="5"
            />
          </el-form-item>

          <!-- 试题标签 -->
          <el-form-item label="试题标签：" prop="tags">
            <el-select
              v-model="qsForm.tags"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="请选择试题标签"
            >
              <el-option
                v-for="item in tagsOptions"
                :key="item.value"
                :label="item.label"
                :value="item.label"
              />
            </el-select>
          </el-form-item>

          <!-- 确认按钮  -->
          <el-form-item>
            <el-button v-if="!$route.query.id" type="primary" @click="submit()">确认提交</el-button>
            <el-button v-else type="success" @click="clickEdit">确认修改</el-button>
          </el-form-item>
        </el-form>

      </div>
    </el-card>
  </div>
</template>

<script>
import { simple as getSubjectsList } from '@/api/hmmm/subjects'
import { simple as getDirectorys } from '@/api/hmmm/directorys'
import { list as getEnterprise } from '@/api/hmmm/companys'
import { provinces as getProvince, citys as getCitys } from '@/api/hmmm/citys'
import { simple as getTagsList } from '@/api/hmmm/tags'
import { direction, questionType, difficulty } from '@/api/hmmm/constants'
import { add, detail, update } from '@/api/hmmm/questions'

import { quillEditor } from 'vue-quill-editor' // 富文本
import hljs from 'highlight.js' //  富文本代码高亮
import 'highlight.js/styles/atom-one-dark.css' // 富文本代码高亮样式

import 'quill/dist/quill.core.css' // 富文本样式
import 'quill/dist/quill.snow.css'
import 'quill/dist/quill.bubble.css'
export default {
  name: 'QuestionsNew',
  components: {
    quillEditor
  },
  data() {
    return {
      qsForm: {
        subjectID: '', // 学科
        catalogID: '', // 目录
        enterpriseID: '', // 企业
        province: '', // 城市
        city: '', // 地区
        direction: '', // 方向
        questionType: '1', // 题型
        difficulty: '1', // 难度
        tags: null, // 试题标签
        question: '', // 题干
        // 选项
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ],
        answer: '', // 答案解析
        videoURL: '', // 解析视频
        remarks: '' // 题目备注
      },
      // 校验规则
      qsRules: {
        subjectID: [
          { required: true, message: '请选择学科' }
        ],
        catalogID: [
          { required: true, message: '请选择目录' }
        ],
        enterpriseID: [
          { required: true, message: '请选择企业' }
        ],
        city: [
          { required: true, message: '请选择地区' }
        ],
        direction: [
          { required: true, message: '请选择方向' }
        ],
        questionType: [
          { required: true, message: '请选择题型' }
        ],
        difficulty: [
          { required: true, message: '请选择难度' }
        ],
        question: [
          { required: true, message: '请输入题干', trigger: 'blur' }
        ],
        answer: [
          { required: true, message: '请输入答题解析', trigger: 'blur' }
        ],
        videoURL: [
          { required: true, message: '请输入视频地址' }
        ],
        remarks: [
          { required: true, message: '请输入视频地址' }
        ],
        tags: [
          { required: true, message: '请输入视频地址' }
        ],
      },
      // 学科列表
      subjectsList: [],
      // 目录列表
      catalogList: [],
      // 企业列表
      enterpriseList: [],
      // 城市列表
      provinceList: getProvince(),
      // 城市下地区列表
      citysList: [],

      // 方向列表
      directionList: direction,

      // 题型选项
      questionType,

      // 难度选项
      difficulty,

      // 标签选项
      tagsOptions: [],

      /*
       放置题干富文本放图片上传配置参数用的
       editorOption里是放图片上传配置参数用的，例如：
       action:  '/api/product/richtext_img_upload.do',  // 必填参数 图片上传地址
       methods: 'post',  // 必填参数 图片上传方式
       token: '',  // 可选参数 如果需要token验证，假设你的token有存放在sessionStorage
       name: 'upload_file',  // 必填参数 文件的参数名
       size: 500,  // 可选参数   图片大小，单位为Kb, 1M = 1024Kb
       accept: 'multipart/form-data, image/png, image/gif, image/jpeg, image/bmp, image/x-icon,image/jpg'  // 可选 可上传的图片格式
      */
      editorOption: {
        placeholder: '',
        modules: {
          toolbar: [
            ['bold', 'italic', 'underline', 'strike'],
            [{ list: 'ordered' }, { list: 'bullet' }],
            ['blockquote'],
            ['code-block', 'image', 'link']
          ],
          // 语法高亮
          syntax: {
            highlight: text => hljs.highlightAuto(text).value
          }
        }
      }
    }
  },
  created() {
    this.showSubjectsList() // 重新发送请求获取学科
    this.clickEnterprise() // 重新获取企业
    if (this.$route.query.id) {
      this.getQuestion(this.$route.query.id)
    } else {
      this.qsForm = {
        subjectID: null,
        catalogID: null,
        enterpriseID: null,
        province: null,
        city: null,
        direction: null,
        questionType: '1',
        difficulty: '1',
        question: null,
        options: [
          { isRight: false, code: 'A', title: '', img: '' },
          { isRight: false, code: 'B', title: '', img: '' },
          { isRight: false, code: 'C', title: '', img: '' },
          { isRight: false, code: 'D', title: '', img: '' }
        ]
      }
      this.$nextTick(() => {
        this.$refs.form.clearValidate()
      })
    }
  },
  methods: {
    async getQuestion(id) {
      const { data } = await detail({ id })
      // console.log(data)
      data.tags = data.tags.split(',')
      data.options = data.options.map(item => {
        item.isRight = item.isRight === 1
        return item
      })

      this.qsForm = data

      // 重新发送请求获取目录
      const res = await getDirectorys({ subjectID: this.qsForm.subjectID })
      // console.log(res)
      this.catalogList = res.data
    },
    async showSubjectsList() { // 获取学科列表
      const res = await getSubjectsList()
      // console.log(res.data, '123123231')
      this.subjectsList = res.data
    },
    async clickEnterprise() { // 获取企业
      const res = await getEnterprise()
      this.enterpriseList = res.data.items
      // console.log(this.enterpriseList)
    },
    getCityList(cityName) {
      // console.log(cityName)
      this.qsForm.city = []
      this.citysList = getCitys(cityName)
    },
    async subjectsChange(subjectID) {
      // console.log(subjectID)
      const res = await getDirectorys({ subjectID: subjectID })
      // console.log(res)
      this.catalogList = res.data
      const res2 = await getTagsList({ subjectID: this.qsForm.subjectID })
      // console.log('标签', res2)
      this.tagsOptions = res2.data
      // console.log('标签', this.tagsOptions)
    },
    changeRadio(item) {
      // 修改后清除所有选中的
      this.qsForm.options.forEach(item => {
        item.isRight = false
      })
      // 自己选中
      item.isRight = true
    },
    changeQuestionType() {
      this.qsForm.options.forEach(item => {
        item.isRight = false
      })
    },
    async submit() {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      // console.log(this.qsForm)
      await add({ ...this.qsForm, tags: this.qsForm.tags.join() })
      this.$message.success('添加成功')
      this.$router.push('/questions/list')
    },
    clickOption() { // 增加选项与答案
      this.qsForm.options.push({
        /*
                  将字母转为ascii嘛的方法：

          var str = "A";
          str.charCodeAt();  // 65

          var str1 = 'a';
          str1.charCodeAt();  // 97
          1
          2
          3
          4
          5
          将ascii码转为对应字母的方法：

          var num = 97;
          String.fromCharCode(num);  // 'a'

          var num1 = 100;
          String.fromCharCode(num1);  // 'd'
        */
        isRight: false,
        code: String.fromCharCode(65 + this.qsForm.options.length), // asc码转换
        title: '',
        img: ''
      })
    },
    async clickEdit() {
      try {
        await this.$refs.form.validate()
      } catch {
        return
      }
      // console.log(this.qsForm)
      await update({ ...this.qsForm, tags: this.qsForm.tags.join() })
      this.$message.success('修改成功')
      // this.$router.push('/questions/list')
      this.$router.go(-1)
    }
  }
}
</script>

<style scoped lang='scss'>
  .container {
    padding: 20px;
    ::v-deep {
      .ql-toolbar {
        height: 36px;
        // line-height: 36px;
        display: flex;
        align-items: center;
      }
      .ql-editor{
        height: 200px;
      }
    }
    .box-card {
      background-color: #fff;
      .content{
        padding-left: 30px;
      }
    }
  }
.avatar-uploader{
  display: inline-block;
  vertical-align: middle;
  line-height: 1;
    ::v-deep {
      .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 10px;
        display: flex;
        align-items: center;
        justify-content: center;
        width: 100px;
        height: 60px;
        position: relative;
        i {
            position: absolute;
            right: 0;
            top: 0;
            transform: translate(50%,-50%);
            background: #fff;
            font-size: 18px;
            color: #999;
        }
      }
      .el-upload:hover {
        border: 1px dashed #409EFF;
      }
    }
}
  .avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 100px;
    height: 60px;
    line-height: 60px;
    text-align: center;
  }
  .avatar {
    width: 78px;
    height: 78px;
    display: block;
  }
</style>
